package com.ikkong.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ikkong.anlis.model.AnliLogsd;
import com.ikkong.anlis.model.Anlis;
import com.ikkong.articles.model.Articles;
import com.ikkong.common.vo.LoginLog;
import com.ikkong.common.vo.User;
import com.ikkong.core.aop.AopContext;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.interfaces.IQuery;
import com.ikkong.core.jfinal.ext.kit.JLogKit;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.model.AjaxResult;
import com.ikkong.core.toolbox.Func;
import com.ikkong.core.toolbox.Record;
import com.ikkong.core.toolbox.kit.DateKit;
import com.ikkong.core.toolbox.log.LogManager;
import com.ikkong.discount.model.DiscountLogs;
import com.ikkong.goods.model.MallGoods;
import com.ikkong.huoyuan.model.Huoyuan;
import com.ikkong.indexs.model.Banner;
import com.ikkong.indexs.model.IndexButtons;
import com.ikkong.indexs.model.IndexNotice;
import com.ikkong.indexs.model.IndexYuqing;
import com.ikkong.juanzhu.model.ReJuanzhu;
import com.ikkong.juanzhu.model.SureJuanzhu;
import com.ikkong.order.model.MallOrder;
import com.ikkong.system.controller.base.UrlPermissController;
import com.ikkong.system.meta.intercept.OrderIntercept;
import com.ikkong.system.model.Dept;
import com.ikkong.system.util.CommonUtil;
import com.ikkong.system.util.SendMessageUtil;
import com.ikkong.xuqiu.model.Xuqiu;
import com.ikkong.yuyue.model.Yuyue;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.beetl.sql.core.kit.StringKit;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * Generated by Blade.
 * 2016-10-08 15:59:45
 */
public class ApiController extends UrlPermissController {
    private static final Prop PROP = PropKit.append("wxpay.properties");
    private static final String USER_PAYING = "USERPAYING";

    public void test(){
        String para = getPara("fname");
        String lname = getPara("lname");
        System.out.println(para);
    }
    public void test2(){
        String accessToken = CommonUtil.getAccessToken();
        String jsTicket = CommonUtil.getJsTicket(accessToken);
        renderJson(success("success"));
    }

    public void mobileIndex(){
        this.render("/mobile_index.html");
    }

    public void sendCode() {
        String tel = getPara("tel");
        if (StringKit.isBlank(tel)) {
            renderJson(error("请输入手机号"));
            return;
        }
        Random random = new Random();
        int r = random.nextInt(899999) + 100000;
        Integer isHas = Blade.dao().selectSingle("User.isHasTel", Record.create().set("tel", tel), Integer.class);
        boolean isSave = false;
        if (isHas > 0) {
            int update = Blade.dao().update("User.updateCode", Record.create().set("code", r).set("tel", tel).set("code_time", new Date()));
            if (update > 0) {//更新成功
                isSave = true;
            } else {
                System.out.println("error1");
                renderJson(error("服务器超时，请稍后再试"));
                return;
            }
        } else {
            User user = new User();
            user.setPhone(tel);
            user.setAccount(tel);
            user.setTel_code(r);
            user.setCode_time(new Date());
            user.setStatus(3);
            user.setMylike_cart("[{\"id\":1,\"title\":\"品牌设计\"},{\"id\":2,\"title\":\"营销推广\"},{\"id\":3,\"title\":\"IT/软件\"}]");
            String salt = ShiroKit.getRandomSalt(5);
            String pwdMd5 = ShiroKit.md5("123456", salt);
            user.setPassword(pwdMd5);
            user.setVersion(0);
            boolean save = Blade.create(User.class).save(user);
            if (save) {
                isSave = true;

            } else {
                System.out.println("error2");
                renderJson(error("服务器超时，请稍后再试"));
                return;
            }
        }

        if (isSave) {
            //在这里写发送短信的逻辑
            boolean b = SendMessageUtil.sendByMoban(r, tel);
            if (b == true) {
                renderJson(success("短信发送成功"));
            } else {
                renderJson(error("短信发送失败，请稍后再试"));
            }
        } else {
            System.out.println("error3");
            renderJson(error("服务器超时，请稍后再试"));
        }

    }


    @Before(POST.class)
    public void doLoginByCode(){
        String account = getPara("tel");
        String code = getPara("code");
        Map map = Blade.dao().selectSingle("User.passwordbycode", Record.create().set("account", account), Map.class);
        String userid = map.get("id").toString();
        if(map == null){
            renderJson(error("验证码验证失败，请重新获取验证码"));
            return;
        }else {
            if(map.get("tel_code") == null){
                renderJson(error("验证码验证失败，请重新获取验证码"));
                return;
            }else {
                if(!map.get("tel_code").toString().equals(code)){
                    renderJson(error("验证码错误"));
                    return;
                }
                Date date = (Date)map.get("code_time");
                Date afterMin = DateKit.getAfterMin(-10);
                if(date.after(afterMin)){//验证码在有效期内
                    if((int)map.get("status")==3){
                        int firstLogin = Blade.dao().update("User.firstLogin", Record.create().set("account", account));
                    }
                    doLog(ShiroKit.getSession(), "登录");
                    Map user = Blade.dao().selectSingle("Api.getUserInfo", Record.create().set("account", account), Map.class);
                    renderJson(Record.create().set("code",0).set("user",user).set("message","登录成功"));
                    return;
                }else {
                    renderJson(error("验证码已过期，请重新获取"));
                    return;
                }
            }
        }
    }


    @Before(POST.class)
    public void updatePassword(){
        String account = getPara("account");
        String password = getPara("password");
        String code = getPara("code");
        Map map = Blade.dao().selectSingle("User.telcode", Record.create().set("account", account), Map.class);
        if(map == null){
            renderJson(error("请重新获取验证码"));
            return;
        }else {
            if(map.get("tel_code") == null){
                renderJson(error("请重新获取验证码"));
                return;
            }else {
                if (!map.get("tel_code").toString().equals(code)) {
                    renderJson(error("验证码错误"));
                    return;
                }
                Date date = (Date)map.get("code_time");
                Date afterMin = DateKit.getAfterMin(-10);
                if(date.after(afterMin)){//验证码在有效期内
                    String salt = ShiroKit.getRandomSalt(5);
                    String pwdMd5 = ShiroKit.md5(password, salt);
                    int update = Blade.dao().update("User.updatePassword", Record.create().set("password", pwdMd5).set("salt", salt).set("tel", account));
                    if(update >0){
                        renderJson(success("修改成功"));
                        return;
                    }
                }else {
                    renderJson(error("修改失败"));
                    return;
                }
            }
        }
    }





    public void myIndex(){
        Map map = new HashMap();
        Object cartList = getCartList();
        Object banner = getBanner();
        map.put("banner",banner);
        map.put("cartList",cartList);

        renderJson(json(map));

    }

    private Object getCartList(){
        List<Object> all = Blade.create(IndexButtons.class).findAll();
       return all;
    }

    private Object getYiqing(){
        Object byId = Blade.create(IndexYuqing.class).findById(1);
        return byId;
    }

    private Object getIndexGoods(){
        List<Map> select = Blade.dao().select("MallGoods.top10", Map.class);
        return select;
    }

    public void getMoreGoods(){
        Object paginate = paginate("MallGoods.mobilelist");
        renderJson(paginate);
    }

    private Object getBanner(){
        List<Object> all = Blade.create(Banner.class).findAll();
        return (all);
    }

    public void getAnlis(){
        Object paginate = paginate("Anlis.list");
        renderJson(paginate);
    }

    public void getArtical(){
        String turn_to = getPara("turn_to");
        Object byId = Blade.create(Articles.class).findById(turn_to);
        renderJson(byId);
    }

    public void takeDiscount(){
        int userid = getParaToInt("userid");
        int discount_id = getParaToInt("discount_id");
        DiscountLogs dl = new DiscountLogs();
        dl.setAddtime(new Date());
        dl.setD_id(discount_id);
        dl.setUser_id(userid);
        dl.setIs_use(0);
        boolean save = Blade.create(DiscountLogs.class).save(dl);
        if(save){
            renderJson(success("领取成功"));
        }else{
            renderJson(error("领取失败"));
        }

    }

    public void myDiscountList(){
        String userid = getPara("userid");
        String dids = Blade.dao().selectSingle("Discount.findLogsNotUse", Record.create().set("userid", userid), String.class);
        String sql = "SELECT * FROM discount where 1 = 1" ;

        if(StringKit.isNotBlank(dids)){
            sql = sql+ " and id IN ("+dids+")";
        }else{
            renderJson(json(new ArrayList<>()));
            return;
        }
        sql = sql + " AND limit_time > NOW() " +
                "ORDER BY limit_time ASC ";
        List<Record> records = Db.init().selectList(sql);
        renderJson(json(records));
    }

    public void getDiscountList(){
        String userid = getPara("userid");
        String dids = Blade.dao().selectSingle("Discount.findLogs", Record.create().set("userid", userid), String.class);
        String sql = "SELECT * FROM discount where 1 = 1" ;

        if(StringKit.isNotBlank(dids)){
            sql = sql+ " and id not IN ("+dids+")";
        }
        sql = sql + " AND limit_time > NOW() " +
                "ORDER BY limit_time ASC ";
        List<Record> records = Db.init().selectList(sql);
        renderJson(json(records));
    }

    public void yuyueSubmit(){
        String name = getPara("name");
        String tel = getPara("tel");
        String position = getPara("position");
        String sex = getPara("sex");
        int userid = getParaToInt("userid");


        Yuyue yuyue = new Yuyue();
            yuyue.setUserid(userid);
            yuyue.setAddtime(new Date());
            yuyue.setName(name);
            yuyue.setTel(tel);
            yuyue.setPosition(position);
            yuyue.setSex(sex);
        boolean save = Blade.create(Yuyue.class).save(yuyue);
        if(save){
            renderJson(success("提交成功"));
        }else {
            renderJson(error("提交失败"));
        }
    }

    private boolean readAdd(Integer id){
        Anlis anlis = Blade.create(Anlis.class).findById(id);
        anlis.setRead_num(anlis.getRead_num()!=null?anlis.getRead_num()+1:1);
        boolean update = Blade.create(Anlis.class).update(anlis);
        return update;
    }

    public void getAnliDetail(){
        Integer id = getParaToInt("id");
        Anlis al= Blade.create(Anlis.class).findById(id);
        if(al==null){
            renderJson("没有找到此案例");
            return;
        }
        readAdd(id);
        List<AnliLogsd> anlilogs = Blade.dao().select("Anlis.logs", AnliLogsd.class, Record.create().set("anli", id));
        renderJson(json(Record.create().set("anli",al).set("logs",anlilogs)));
    }

    private Object getNotice(){
        Object firstBy = Blade.create(IndexNotice.class).findFirstBy("", IndexNotice.class);
        return (firstBy);
    }


    public void reJuanzhu(){
        String person = getPara("person");
        String tel = getPara("tel");
        String money = getPara("money");
        String something = getPara("something");
        ReJuanzhu reJuanzhu = new ReJuanzhu();
        reJuanzhu.setPerson(person);
        reJuanzhu.setTel(tel);
        if(StringKit.isNotBlank(money)){
            reJuanzhu.setMoney(new BigDecimal(money));
        }
        reJuanzhu.setSomething(something);
        reJuanzhu.setAddtime(new Date());
        boolean save = Blade.create(ReJuanzhu.class).save(reJuanzhu);
        if(save){
            renderJson(success("提交成功"));
        }else {
            renderJson(error("提交失败"));
        }
    }

    public void sendHuoyuan(){
        String person = getPara("person");
        String tel = getPara("tel");
        String title = getPara("title");
        String guige = getPara("guige");
        String price = getPara("price");
        Integer num = getParaToInt("num");
        Huoyuan huoyuan = new Huoyuan();
        huoyuan.setAddtime(new Date());
        huoyuan.setStatus(1);
        huoyuan.setPerson(person);
        huoyuan.setTel(tel);
        huoyuan.setTitle(title);
        huoyuan.setPrice(price);
        huoyuan.setNum(num);
        huoyuan.setGuige(guige);
        boolean save = Blade.create(Huoyuan.class).save(huoyuan);
        if(save){
            renderJson(success("提交成功"));
        }else {
            renderJson(error("提交失败"));
        }
    }

    public void sendXuqiu(){
        String person = getPara("person");
        String tel = getPara("tel");
        String title = getPara("title");
        String company = getPara("company");
        String address = getPara("address");
        String content = getPara("content");
        Integer num = getParaToInt("num");
        Xuqiu xuqiu = new Xuqiu();
        xuqiu.setAddtime(new Date());
        xuqiu.setStatus(1);
        xuqiu.setContent(content);
        xuqiu.setPerson(person);
        xuqiu.setTel(tel);
        xuqiu.setTitle(title);
        xuqiu.setCompany(company);
        xuqiu.setNum(num);
        xuqiu.setAddress(address);
        boolean save = Blade.create(Xuqiu.class).save(xuqiu);
        if(save){
            renderJson(success("提交成功"));
        }else {
            renderJson(error("提交失败"));
        }
    }

    public void xuqiuList(){
        Object paginate = paginate("Xuqiu.mobilelist");
        renderJson(paginate);
    }
    public void juanzhuText(){
        List<Map> select = Blade.dao().select("SureJuanzhu.juanzhuTextList", Map.class, null);
        renderJson(json(select));
    }

    public void huoyuanList(){
        Object paginate = paginate("Huoyuan.mobilelist");
        renderJson(paginate);
    }


    public void huoyuanDetail(){
        String id = getPara("id");
        Huoyuan byId = Blade.create(Huoyuan.class).findById(id);
        renderJson(json(byId));
    }

    public void xuqiuDetail(){
        String id = getPara("id");
        Xuqiu byId = Blade.create(Xuqiu.class).findById(id);
        renderJson(json(byId));
    }

    public void goodsDetail(){
        String id = getPara("id");
        int uid = getParaToInt("userid");
        if( ShiroKit.getUser()!=null){
            uid = Integer.parseInt(ShiroKit.getUser().getId().toString());
        }
        Integer count = Blade.dao().selectSingle("Api.myYuyue", Record.create().set("uid", uid).set("gid", id), Integer.class);
        MallGoods goods = Blade.create(MallGoods.class).findById(id);
        goods.setKucun(goods.getBuy_num()-goods.getSale_num());
        Record parse = Record.parse(goods);
        if(count == 0){
            parse.put("is_yuyue",false);
        }else {
            parse.put("is_yuyue",true);
        }
        renderJson(json(parse));
    }

    public void myYuyue(){
        Object paginate = paginate("Yuyue.list");
        renderJson(paginate);

    }


    public void juanzhuList(){
        Object paginate = paginate("SureJuanzhu.mobilelist");
        renderJson(paginate);
    }


    private boolean isLogin(String account){
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, "123456".toCharArray());
        String remberme = getPara("remberme","1");
        if(remberme.equals("1")){
            token.setRememberMe(true);
        }else {
            token.setRememberMe(false);
        }
        try {
            currentUser.login(token);
            Session session = ShiroKit.getSession();
            JLogKit.println("sessionID	: {} ", session.getId());
            JLogKit.println("sessionHost	: {}", session.getHost());
            JLogKit.println("sessionTimeOut	: {}", session.getTimeout());
        } catch (UnknownAccountException e) {
            LogKit.error("账号不存在：{}", e);
            renderJson(error("账号不存在"));
            return false;
        } catch (DisabledAccountException e) {
            LogKit.error("账号未启用：{}", e);
            renderJson(error("账号未启用"));
            return false;
        } catch (IncorrectCredentialsException e) {
            LogKit.error("密码错误：{}", e);
            renderJson(error("密码错误"));
            return false;
        } catch (RuntimeException e) {
            LogKit.error("未知错误,请联系管理员：{}", e);
            renderJson(error("未知错误,请联系管理员"));
            return false;
        }
        doLog(ShiroKit.getSession(), "登录");
        return true;
    }





//    微信登录
    public void loginByWxCode(){
        String code = getPara("code");
        if(StringKit.isBlank(code)){
            renderJson(error("参数错误"));
            return;
        }
        String json = CommonUtil.codeToOpenid(code);
        Map parse = JsonKit.parse(json, Map.class);
        String openid = "";
        if(parse!=null){
            try {
                String s = parse.get("openid").toString();
                openid = s;
            }catch (Exception e){
                System.out.println(e);
            }
        }
        if(StringKit.isNotBlank(openid)){
            setSessionAttr("openid",openid);
            Map wxUser = Blade.dao().selectSingle("Api.getUserInfoByOpenid", Record.create().set("openid", openid), Map.class);
            if(wxUser == null){//没有这个openid，创建用户
                User user = new User();
                user.setName("微信用户");
                user.setAvatar("/upload/icons/Sun.png");
                Map wxUserInfo = CommonUtil.getWxUserInfo(openid);
                try {
                    String nickname = wxUserInfo.get("nickname").toString();
                    user.setName(nickname);
                    String headimgurl = wxUserInfo.get("headimgurl").toString();
                    user.setAvatar(headimgurl);
                }catch (Exception e){
                    System.out.println(e);
                }finally {
                    user.setPhone("");
                    user.setAccount(openid.substring(6));
                    user.setStatus(1);
                    String salt = ShiroKit.getRandomSalt(5);
                    String pwdMd5 = ShiroKit.md5("123456", salt);
                    user.setPassword(pwdMd5);
                    user.setSalt(salt);
                    user.setVersion(0);
                    user.setOpenid(openid);
                    user.setCreatetime(new Date());
                    user.setDeptid(2);
                    user.setRoleid(8+"");
                    Integer save = Blade.create(User.class).saveRtId(user);
                    if(save != null){
//                        redirect("/mobile/api/doLogin?account="+user.getAccount());
                        boolean login = isLogin(user.getAccount());
                        if(login){
                            renderJson(json(Record.create()
                            .set("nickname",user.getName()).set("avatar",user.getAvatar()).set("userid",user.getId())));
                        }else {
                            renderJson(error("登录失败"));
                        }
                    }else{
                        renderJson(error("登录失败，请重新登录"));
                        return;
                    }
                }
            }else {//有该用户直接登录
                        boolean account = isLogin(wxUser.get("account").toString());
                        if(account){
                            renderJson(json(Record.create()
                                    .set("nickname",wxUser.get("name")).set("avatar",wxUser.get("avatar")).set("userid",wxUser.get("id"))));
                        }else {
                            renderJson(error("登录失败"));
                        }
                    }
        }
       else {
            renderJson(error("获取微信授权失败"));
        }
    }





    public void bindTel(){
        String tel = getPara("tel");
        Integer userid = getParaToInt("userid");
        String code = getPara("code");
        User user = Blade.create(User.class).findById(userid);
        Integer isHas = Blade.dao().selectSingle("User.isHasTelStatus", Record.create().set("tel", tel), Integer.class);
        if(isHas > 0){
            renderJson(error("该号码已被绑定"));
            return;
        }
        Map newAccount = Blade.dao().selectSingle("Api.queryByphone", Record.create().set("tel", tel), Map.class);
        if(newAccount == null){
            renderJson(error("验证码获取失败"));
            return;
        }
        String tel_code = newAccount.get("tel_code").toString();
        Date code_time = (Date) newAccount.get("code_time");
        if(code_time.before(DateKit.getAfterMin(-10))){//验证码过期
            renderJson(error("验证码过期，请重新获取"));
            return;
        }else {
            if(code.equals(tel_code)){
                user.setAccount(tel);
                user.setPhone(tel);
                user.setStatus(1);
                user.setUpdatetime(new Date());
                boolean update = Blade.create(User.class).update(user);
                if (update) {
                    int delSameTel = Blade.dao().update("Api.delSameTelUser", Record.create().set("userid", userid).set("tel", tel));
                    if(StringKit.isNotBlank(user.getOpenid())){
                        int delSameOpenid = Blade.dao().update("Api.delSameOpenidUser", Record.create().set("userid", userid).set("openid", user.getOpenid()));
                    }
                    Dept dept = Blade.create(Dept.class).findById(user.getDeptid());
                    AjaxResult res = json(Record.create().set("user", Record.create().set("avatar",user.getAvatar()).
                            set("id", user.getId()).set("name", user.getName()).set("phone",user.getPhone()).
                            set("deptid", user.getDeptid()).set("deptname", dept.getFullname())),"绑定成功");
                    renderJson(res);
                }else {
                    renderJson(error("绑定失败"));
                }
            }else {
                renderJson(error("验证码错误"));
            }
        }
    }

    public void doLog(Session session, String type){
        if(!LogManager.isDoLog()){
            return;
        }
        try{
            LoginLog log = new LoginLog();
            String msg = Func.format("[sessionID]: {} [sessionHost]: {} [sessionHost]: {}", session.getId(), session.getHost(), session.getTimeout());
            log.setLogname(type);
            log.setMethod(msg);
            log.setCreatetime(new Date());
            log.setSucceed("1");
            log.setUserid(Func.format(ShiroKit.getUser().getId()));
            Blade.create(LoginLog.class).save(log);
        }catch(Exception ex){
            LogKit.logNothing(ex);
        }
    }





    /*
   文件上传+改文件名
    */
    public void upload(){
        String fileName = "";
        boolean flag = false;
        String msg = "";
        String rename = "";
        UUID uuid = UUID.randomUUID();
        try {
            UploadFile avatar = getFile("file","/",31457280);
            File file = avatar.getFile();
            fileName = file.getName();
            int one = fileName.lastIndexOf(".");
            Date d = new Date();
            rename ="/upload/"+ uuid + fileName.substring(one);
            boolean b = file.renameTo(new File(avatar.getUploadPath(), uuid + fileName.substring(one)));
            msg = "success";
            flag = true;
        }catch (Exception e) {
            msg = "网络超时，请重试。";
        }
        JSONObject json = new JSONObject();
        json.put("flag", flag);
        json.put("msg", msg);
        json.put("code",0);
        json.put("fileName", rename);
        renderJson(json);
    }

    public void updateLogo(){
        String logo = getPara("logo");
        String userid = getPara("userid");
        if(StringKit.isBlank(logo) || StringKit.isBlank(userid)){
            renderJson(error("未传入完整信息"));
            return;
        }
        int update = Blade.dao().update("Api.updateLogo", Record.create().set("logo", logo).set("userid", userid));
        if(update>0){
            renderJson(success("修改头像成功"));
        }else {
            renderJson(error("修改头像失败"));

        }
    }


    public void myOrders(){
        Object paginate = paginate("MallOrder.list");
        renderJson(paginate);
    }

    public void orderBanner(){
        List<Object> all = Blade.create(Banner.class).findAll();
        renderJson(json(all));
    }





    public void bindOpenid(){
        String code = getPara("code");
        Integer userid = getParaToInt("userid");
        String json = CommonUtil.codeToOpenid(code);
        Map parse = JsonKit.parse(json, Map.class);
        String openid = "";
        if(parse!=null){
            try {
                String s = parse.get("openid").toString();
                openid = s;
            }catch (Exception e){
                System.out.println(e);
                renderJson(error(json));
                return;
            }
        }
        User user = new User();
        user.setId(userid);
        user.setUpdatetime(new Date());
        user.setOpenid(openid);
        boolean update = Blade.create(User.class).update(user);
        if(update){
            renderJson(success("授权成功"));
        }else{
            renderJson(error("授权失败"));
        }
    }




    public void testPay(){
        Map<String, String[]> paraMap = getParaMap();
        System.out.println(paraMap.toString());
        String xmlMsg = HttpKit.readData(getRequest());
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String resultCode = params.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            renderJson("支付不成功");
            return;
        }
        String out_trade_no = params.get("out_trade_no");
        if(StringKit.isBlank(out_trade_no)){
            LogKit.info("支付订单号错误");
            renderJson(error("支付订单号错误"));
        }else {
            if(out_trade_no.contains("A0000000000A")){
                if(out_trade_no.contains("A0000000000AB")){
                    out_trade_no = out_trade_no.replaceAll("A0000000000AB","");
                   out_trade_no =  out_trade_no.substring(3);
                }else {
                    out_trade_no = out_trade_no.replaceAll("A0000000000A","");
                }
                MallOrder order = Blade.create(MallOrder.class).findById(out_trade_no);
                if(order.getStatus()==1){
                    order.setPay_time(new Date());
                    order.setIs_pay(1);
                    order.setPay_time(new Date());
                    order.setStatus(2);
                    boolean update = Blade.create(MallOrder.class).update(order);
                    if(update){
                        Blade user = Blade.create(User.class);
                        try {
                            boolean mes = CommonUtil.pushMes((User)user.findById(order.getU_id()), out_trade_no + "", "付款成功");
                        }catch (Exception e){
                            System.out.println(e);
                        }
                        renderJson(success("订单更新成功"));
                    }else {
                        renderJson(error("订单更新失败"));
                    }
                }else {
                    renderJson(error("订单不存在或已经处理完"));
                }
            }

        }

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态

//        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey())) {
//            if (WxPayKit.codeIsOk(resultCode)) {
//                // 更新订单信息
//                // 发送通知等
//                Map<String, String> xml = new HashMap<String, String>(2);
//                xml.put("return_code", "SUCCESS");
//                xml.put("return_msg", "OK");
//                renderText(WxPayKit.toXml(xml));
//                return;
//            }
//        }
//        renderText("");
    }


    public void shareData(){
        String type = getPara("type");
        String id = getPara("id");
        String link = getPara("link");

        Map map = new HashMap();
        if(type.equals("index")){
            map.put("title","美家居全屋定制");
            map.put("desc","美家居全屋定制简介");
            map.put("link",link);
            map.put("imgUrl","http://nsl.nnruanyun.com/zhuangxiu.jpg");
        }else if(type.equals("detail")){
//            link = link.replace("?from=singlemessage","");
//            link= link + "?id="+id;
            Anlis anlis = Blade.create(Anlis.class).findById(id);
            map.put("title",anlis.getTitle());
            map.put("desc",anlis.getDetail());
            map.put("link",link);
            map.put("imgUrl",anlis.getPic());
        }else if(type.equals("info")){
//            link = link.replace("?from=singlemessage","");
//            link= link + "?id="+id;
            Articles ari = Blade.create(Articles.class).findById(id);
            map.put("title",ari.getTitle());
            map.put("desc",ari.getRemarks());
            map.put("link",link);
            map.put("imgUrl","http://nsl.nnruanyun.com/zhuangxiu.jpg");
        }else{
            map.put("title","美家居全屋定制");
            map.put("desc","美家居全屋定制简介");
            map.put("link",link);
            map.put("imgUrl","http://nsl.nnruanyun.com/zhuangxiu.jpg");
        }
        Map shareSign = CommonUtil.getShareSign(link);
//        Map shareSign = sign.sign("HoagFKDcsGMVCIY2vOjf9qoItpoe9en8FfUCvJ5Nay4eFTc-MXacy7HIvguRvEJoFwr9_4UCvUTrpj4cKMFMJA",
//                link, sign.create_timestamp());
//        System.out.println(shareSign);

//        Record shareSign = Record.create().set("signature", "8f89fcf3f10ffe755740513c95979b93398474d3")
//                .set("url", "fx.itshop.top").
//                set("jsapi_ticket", "HoagFKDcsGMVCIY2vOjf9qoItpoe9en8FfUCvJ5Nay4hC-qqUdT35FX_tuNPsx2q3fzvc-ynoNBWBBJyIOAobQ").
//                set("timestamp","1578452866").
//                set("nonceStr", "c5113b10-fe20-4530-a6c8-19a962bc20a6");
        map.put("sign",shareSign);

        renderJson(json(map));
    }


    public void downloadFile(){
        String webRootPath = PathKit.getWebRootPath();
        String rootClassPath = PathKit.getRootClassPath();
        String path = getPara("path");
        File file = new File(webRootPath+path);
        renderFile(file);

    }


}
